<?php

namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Library\Common;
use App\Models\Admin\AdminBonusLog;
use App\Models\Admin\AdminUser;
use App\Models\Admin\AfterSale;
use App\Models\Admin\Configs;
use App\Models\Member\MemberBase;
use App\Models\User\UserBase;
use Illuminate\Http\Request;
use App\Models\Admin\Achievement;
use App\Models\Admin\Salebonusrule;
use Carbon\Carbon;
use Excel;
use Illuminate\Support\Facades\DB;

class AchievementController extends BaseController
{
    protected $fields = array(
        'goods_name' => '',
        'goods_money' => 0,
        'order_number' => '',
        'buy_time' => '',
        'buy_length' => 0,
        'after_sale_id' => 0,
        'remarks' => '',
        'sale_proof' => '',
        "goods_price" => 0
    );

    public function __construct(Request $request){
        parent::__construct($request);
    }

    /* 业绩订单列表 */
    public function dataList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->return_result($this->returnData);
        }
        $page_no = $request->post('page_no', 1);
        $page_size = $request->post('page_size', 10);
        $searchFilter = array(
            'sortName' => $request->post('sortName','id'),                                                  //排序列名
            'sortOrder' => $request->post('sortOrder','desc'),                                              //排序（desc，asc）
            'pageNumber' => $page_no,                                                                                   //当前页码
            'pageSize' => $page_size,                                                                                   //一页显示的条数
            'start' => ($page_no-1) * $page_size,                                                                       //开始位置
            'searchKey' => trim($request->post('search','')),                                               //搜索关键词
            'start_time' => trim($request->post('start_time','')),                                          //订单创建时间(开始)
            'end_time' => trim($request->post('end_time','')),                                              //订单创建时间(结束)
            'branch_id' => trim($request->post('branch_id','')),                                            //团队ID
            'user_id' => trim($request->post('user_id','')),                                                //销售ID
            'status' => trim($request->post('status','')),                                                  //业绩订单状态
            'type' => trim($request->post('type','')),                                                      //商品类型筛选
            'admin_id' => $this->AU['position'] == "超级管理员" ? "" : $this->AU['id'],
            'is_del' => 0
        );
        $achievementModel = new Achievement();
        $res = $achievementModel->getAchievementList($searchFilter);
        foreach ($res["rows"] as &$item){
            if($item["verify_user_id"]) {
                if (empty($temp["verify_user_id"])){
                    $tt = Db::table("admin_users")->select("name")->where("id", $item["verify_user_id"])->first();
                    $temp["verify_user_id"] = $tt->name;
                }
                $item["verify_user_id"] = $temp["verify_user_id"];
            }
            $item['sale_bonus'] = $item['sale_bonus'] > 0 ? $item['sale_bonus'] : $item['bonus_royalty'];
        }
//        $res['total_money'] = $achievementModel->getAchievementTotalMoney($res['rows']);
        $res['total_month'] = $achievementModel->getTotalMoneyBydate(['user_list' => [$this->AU['id']],'date' => date('Y-m')]); //个人当月业绩
        $this->returnData['data'] = $res;
        return $this->return_result($this->returnData);
    }

    /* 个人业绩订单列表 */
    public function getList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $dateTime = $request->dateTime ? strtotime($request->dateTime) : time();
        $start_time = date('Y-m-1 00:00:00', $dateTime); //当月开始时间
        $end_time = date('Y-m-t 23:59:59', $dateTime); //当月结束时间
        $page_no = $request->post('page_no', 1);
        $page_size = $request->post('page_size', 10);
        $searchFilter = array(
            'sortName' => $request->post('sortName','id'),                                                  //排序列名
            'sortOrder' => $request->post('sortOrder','desc'),                                              //排序（desc，asc）
            'pageNumber' => $page_no,                                                                                   //当前页码
            'pageSize' => $page_size,                                                                                   //一页显示的条数
            'start' => ($page_no-1) * $page_size,                                                                       //开始位置
            'searchKey' => trim($request->post('search','')),                                               //搜索关键词
            'start_time' => $start_time,                                          //订单创建时间(开始)
            'end_time' => $end_time,                                              //订单创建时间(结束)
            'user_id' => trim($request->post('user_id','')),                                                //销售ID
            'status' => trim($request->post('status','')),                                                  //业绩订单状态
//            'admin_id' => $this->AU['id'],
            'is_del' => 0
        );
        $achievementModel = new Achievement();
        $res = $achievementModel->getAchievements($searchFilter);
        $res['total_money'] = 0;
        $res['total_bonus_money'] = 0;
        foreach ($res['rows'] as &$item){
            $item['sale_bonus'] = $item['bonus_royalty'] ?: $item['sale_bonus'];
            $res['total_money'] += $item['order_bonus'];
            $res['total_bonus_money'] += $item['sale_bonus'];
        }
        $res['total_money'] = sprintf("%.2f", $res['total_money']);
        $res['total_bonus_money'] = sprintf("%.2f", $res['total_bonus_money']);
        $this->returnData['data'] = $res;
        return $this->return_result($this->returnData);
    }

    /* 业绩订单详情 */
    public function detail($id){
        if ($this->returnData['code'] > 0){
            return $this->return_result($this->returnData);
        }
        $achievementModel = new Achievement();
        $data = $achievementModel->getAchievementById($id);
        if(!is_array($data) || count($data)<1){
            $this->returnData = ErrorCode::$admin_enum['not_exist'];
            $this->returnData['msg'] = '数据不存在';
            return $this->return_result($this->returnData);
        }
        if($this->AU['position'] != "超级管理员") {
            $adminUserModel = new UserBase();
            $user_list = $adminUserModel->getAdminSubuser($this->AU['id']);
            if (!in_array($data['admin_users_id'], $user_list)) {
                $this->returnData = ErrorCode::$admin_enum['auth_fail'];
                return $this->return_result($this->returnData);
            }
        }
        $db = DB::table("after_sale")->select("after_money","bonus_royalty");
        if(!empty($data["number_sn"])){
            $db->where("number_sn", $data["number_sn"]);
        }else{
            $db->where('order_number', '=', $data["order_number"])->where('buy_time', '=', $data["buy_time"]);
        }
        $res = $db->first();
        $res = json_decode(json_encode($res),true);
        $data["after_money"] = isset($res["after_money"]) && $res["after_money"] > 0 ? sprintf("%.2f", $res["after_money"]) : sprintf("%.2f", $data["order_bonus"]);
        $data["bonus_royalty"] = $data["sale_bonus"];
        $data["total_bonus"] = sprintf("%.2f", $data["after_money"] + $data["bonus_royalty"]);
        $data['sale_proof'] = trim($data['sale_proof'],',');
        $data['sale_proof'] = array_values(explode(',',$data['sale_proof']));
        $ress = DB::table("admin_users")->where("id", $data["verify_user_id"])->select("name")->first();
        $ress = json_decode(json_encode($ress),true);
        $data['verify_user_name'] = $ress['name'];
        $member_info = DB::table('member as m')
            ->select('me.realname','me.company','me.qq','me.wechat','me.type','me.position','me.source')
            ->leftJoin('member_extend as me','me.member_id','=','m.id')
            ->where('m.mobile','=',$data['member_phone'])
            ->first();
        $member_info = json_decode(json_encode($member_info),true);
        $data['company'] = $member_info['company'];
        $data['qq'] = $member_info['qq'];
        $data['wechat'] = $member_info['wechat'];
        if ($member_info['type'] == 1){
            $data['type'] = '企业';
        }else{
            $data['type'] = '个人';
        }
        if ($data['sale_proof']){
            foreach ($data['sale_proof'] as &$v){
                $v = $this->processingPictures($v);
            }
        }
        $data['position'] = $member_info['position'];
        $data['source'] = $member_info['source'];
        $data['ach_state_text'] = $data['ach_state'] == '0' ? "参与" : "不参与";
        $data['sale_order'] = !empty($res) && $data['after_sale_id'] ? "创建" : "不创建";
        if($data['sbr_id'] && !empty($sbrData = DB::table("salebonusrule")->where(["id" => $data['sbr_id']])->first())){
            $data['ruleName'] = $sbrData->rule_name;
            $data['ruleMode'] = ($sbrData->type == '1' ? "提成" : "奖金") . " - " . ($sbrData->rule_type == '0' ? "按比例" : "按固定");
            $data['ruleCompute'] = "成本{$sbrData->cost}%，销售业绩提成{$sbrData->pre_bonus}%，" . ($sbrData->type == '1' ? "提成{$sbrData->after_bonus}%" : "奖金{$sbrData->bonus}%");
        }else{
            $data['ruleName'] = '';
            $data['ruleMode'] = '';
            $data['ruleCompute'] = '';
        }
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    /* 业绩修改 */
    public function edit(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $id = $request->id;
        $achievement = [];
        foreach (array_keys($this->fields) as $field) {
            /* 验证参数未做 */
            if($request->post($field)===NULL){
                continue;
            }
            $achievement[$field] = $request->post($field,$this->fields[$field]);
        }
        $achievementModel = new Achievement();
        $data = $achievementModel->getAchievementById($id);
        if(!is_array($data)){
            $this->returnData = ErrorCode::$admin_enum['not_exist'];
            return $this->return_result($this->returnData);
        }
        if($this->AU['id']>1 && $this->AU['id'] != $data['admin_users_id']){
            $this->returnData = ErrorCode::$admin_enum['auth_fail'];
            $this->returnData['msg'] = '无权限编辑该订单';
            return $this->return_result($this->returnData);
        }
        $achievement["status"] = 0;
        $res = $achievementModel->achievementUpdate($id,$achievement);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '修改失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '修改成功';
        return $this->return_result($this->returnData);
    }

    /* 更新数据 */
    public function ajax(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if (!isset($request->action) || !in_array(strval($request->action),['status','refuse','refund'],true)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            return $this->return_result($this->returnData);
        }
        $id = $request->id;
        switch ($request->action){
            case 'status':
                $achievementModel = new Achievement();
                $data = $achievementModel->achievementUpdate($id,['status' => $request->status]);
                if(is_array($data)){
                    $this->returnData = ErrorCode::$admin_enum['fail'];
                    $this->returnData['msg'] = '处理失败';
                }
                return $this->return_result($this->returnData);
            case 'refuse':
                $data = $this->_refuseAchievement($request);
                return $this->return_result($data);
            default:
                $this->returnData = ErrorCode::$admin_enum['fail'];
                $this->returnData['msg'] = '未知操作';
                return $this->return_result($this->returnData);
        }
    }

    /* 审核订单 */
    public function verifyRecord(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $id = $request->id;
        $achievementModel = new Achievement();
        $a_res = $achievementModel->getAchievementById($id);
        if(!is_array($a_res)){
            return $this->return_result(ErrorCode::$admin_enum['not_exist']);
        }
        if(!in_array($request->after_type,[0,1,2])){
            return $this->return_result(ErrorCode::$admin_enum['params_error']);
        }
        DB::beginTransaction();
        try {
            $achievement_upd = $saleRuleDetail = [];
            $after_money = $bonus_royalty = 0;
            if ($request->after_type == 0) {
                $saleRuleModel = new Salebonusrule();
                if (empty($saleRuleDetail = $saleRuleModel->getSaleRuleDetail($request->sbr_id))) {
                    return $this->return_result(ErrorCode::code("customized", "提成规则不存在"));
                }
                if ($saleRuleDetail['cost'] > 100) {
                    return $this->return_result(ErrorCode::code("customized", "提成规则错误"));
                }
                //利润 = 售前利润(销售所得) + 售后利润(销售所得) + 余下利润
                // step 1 成本 = 售价 * 成本百分比
                $cost = sprintf('%.2f', $a_res['goods_money'] * $saleRuleDetail['cost'] / 100);
                // step 2 利润 = 售价 - 成本
                $profit = $a_res['goods_money'] - $cost;
                if ($saleRuleDetail['rule_type'] == 0) { // 比例
                    //售前提成
                    $achievement_upd['order_bonus'] = sprintf('%.2f', $profit / 100 * $saleRuleDetail['pre_bonus']);
                    if ($saleRuleDetail['type'] == 1) {  //提成
                        $after_money = sprintf('%.2f', $profit / 100 * $saleRuleDetail['after_bonus']);  //售后提成
                    } else {  //奖金
                        $bonus_royalty = sprintf('%.2f', $profit / 100 * $saleRuleDetail['bonus']);         //售后奖金
                    }
                } else { // 固定金额
                    $achievement_upd['order_bonus'] = $saleRuleDetail['pre_bonus'];        //售前提成
                    if ($saleRuleDetail['type'] == 1) {  //提成
                        $after_money = $saleRuleDetail['after_bonus'];  //售后提成
                    } else {  //奖金
                        $bonus_royalty = $saleRuleDetail['bonus'];         //售后奖金
                    }
                }
            } elseif ($request->after_type == 2) {
                //手写固定金额
                $achievement_upd['order_bonus'] = $request->order_bonus;       //售前提成
                $after_money = 0;       //售后提成
                $bonus_royalty = $request->bonus_money;       //售后奖金
            }
            $sale_data = [
                'after_sale_id' => $request->after_sale_id, "member_name" => $a_res["member_name"],
                "member_phone" => $a_res["member_phone"], "goods_money" => $a_res["goods_money"], "sbr_id" => $request->sbr_id ?: 0,
                "goods_name" => $a_res["goods_name"], "order_number" => $a_res["order_number"], "number_sn" => $a_res["number_sn"],
                "buy_time" => $a_res["buy_time"], "buy_length" => $a_res["buy_length"], "after_type" => $request->after_type,
                'after_money' => $after_money, 'bonus_royalty' => $bonus_royalty, "created_at" => Carbon::now()->toDateTimeString(),
                "updated_at" => Carbon::now()->toDateTimeString(), "mall_id" => $request->mallData["id"]
            ];
            //增加售后记录
            if (!DB::table("after_sale")->insert($sale_data)) {
                DB::rollBack();
                return $this->return_result(ErrorCode::code("customized", "同意失败，添加售后记录失败"));
            }
            $this->returnData['msg'] = '同意成功';
            $userbaseModel = new UserBase();
            if ($after_money > 0){
                $a_res['verify'] = $this->AU['name'];
                $res = $userbaseModel->addBonus($request->after_sale_id,$after_money,$a_res);
                if(!$res){
                    DB::rollBack();
                    return $this->return_result(ErrorCode::code("customized", "发放提成失败"));
                }
            }
            if ($bonus_royalty > 0){
                $a_res['verify'] = $this->AU['name'];
                $res = $userbaseModel->addSaleBonus($request->after_sale_id,$bonus_royalty,$a_res);
                if(!$res){
                    DB::rollBack();
                    return $this->return_result(ErrorCode::code("customized", "发放奖金失败"));
                }
            }
            $achievement_upd['sale_bonus'] = $bonus_royalty;
            $achievement_upd['verify_time'] = Carbon::now();
            $achievement_upd['verify_user_id'] = $this->AU['id'];
            $achievement_upd['ach_state'] = $request->ach_state;
            $achievement_upd['status'] = 1;
            $achievement_upd['sbr_id'] = $request->sbr_id;
            $achievement_upd['after_sale_id'] = $request->after_sale_id;
            $result = $achievementModel->achievementUpdate($id, $achievement_upd);
            if (!$result) {
                DB::rollBack();
                return $this->return_result(ErrorCode::code("customized", "同意失败"));
            }
            $configModel = new Configs();
            $config = $configModel->getConfigByID();
            if ($config['qywxLogin'] == 1){
                //发邮件加自动推送
                $comm = new Common();
                $userData = AdminUser::query()->where("id", $a_res["admin_users_id"])->select("wechat_id")->first();
                $comm->QyWechatPush($userData->wechat_id,'订单号为'.$a_res['order_number'].'的业绩订单审核成功');
            }
        }catch (\Exception $e){
            DB::rollBack();
            return $this->return_result(ErrorCode::code("customized", $e->getMessage().$e->getTraceAsString()));
        }
        DB::commit();
        return $this->return_result($this->returnData);
    }

    /* 拒绝业绩订单 */
    private function _refuseAchievement($request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $id = $request->id;
        $data['status'] = 2;
        $data['refuse_remarks'] = $request->post('refuse_remarks','');
        $data['verify_time'] = Carbon::now();
        $data['verify_user_id'] = $this->AU['id'];
        $achievementModel = new Achievement();
        $res = $achievementModel->achievementUpdate($id,$data);
        if(!$res){
            $r_data = ErrorCode::$admin_enum['fail'];
            $r_data['msg'] = '处理失败';
            return $r_data;
        }
        $fields = ['au.name as admin_name','a.refuse_remarks','au.email','a.order_number','au.wechat_id'];
        $achData = $achievementModel->getAchievementWithAdminData($id,$fields);
        $configModel = new Configs();
        $config = $configModel->getConfigByID(1);
        if ($config['qywxLogin'] == 1) {
            //发邮件加自动推送
            $comm = new \App\Library\Common();
            $comm->QyWechatPush($achData['wechat_id'], '订单号为' . $achData['order_number'] . '的业绩订单审核失败，拒绝备注：' . $achData['refuse_remarks']);
        }
        return $this->returnData;
    }

    /* 业绩导出 */
    public function export(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if (!isset($request->action) || !in_array(strval($request->action),['data'],true)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            return $this->return_result($this->returnData);
        }
        if($request->action=='data'){
            if(trim($request->get('list',''))==''){
                $this->returnData = ErrorCode::$admin_enum['params_error'];
                $this->returnData['msg'] = '勾选列表不能为空';
                return $this->return_result($this->returnData);
            }
            $list = explode(',',trim($request->get('list','')));
            $achievementModel = new Achievement();
            $maxID = $achievementModel->getMaxAchievementID();
            $page_no = $request->get('page_no', 1);
            $page_size = $request->get('page_size', 10);
            $searchFilter = array(
                'sortName' => $request->get('sortName','id'),                                               //排序列名
                'sortOrder' => $request->get('sortOrder','desc'),                                           //排序（desc，asc）
                'pageNumber' => $page_no,                                                                               //当前页码
                'pageSize' => $maxID,                                                                               //一页显示的条数
                'start' => ($page_no-1) * $page_size,                                                                   //开始位置
                'searchKey' => trim($request->get('search','')),                                            //搜索关键词
                'start_time' => trim($request->get('start_time','')),                                       //订单创建时间(开始)
                'end_time' => trim($request->get('end_time','')),                                           //订单创建时间(结束)
                'branch_id' => trim($request->get('branch_id','')),                                         //团队ID
                'user_id' => trim($request->get('user_id','')),                                             //销售ID
                'status' => trim($request->get('status','')),                                               //业绩订单状态
                'admin_id' => $this->AU['position'] == "超级管理员" ? "" : $this->AU['id'],
                'list' => $list,
                'type' => '',
                'is_del' => 0
            );
            $res = $achievementModel->getAchievementList($searchFilter);
            $obj = $res['rows'];
            $arr=[['ID','客户名称','手机','提交人','商品名称','商品金额','订单号','订单提成','备注(拒绝备注)','购买时间','订单状态']];
            foreach($obj as $key => $val){
                if($val['refuse_remarks']){
                    $remarks = $val['remarks'].'('.$val['refuse_remarks'].')';
                }else{
                    $remarks = $val['remarks'];
                }
                if($val['status']==0){
                    $status = '审核中';
                }else if($val['status']==1){
                    $status = '审核成功';
                }else{
                    $status = '拒绝';
                }
                $arr[] = array(
                    $val['id'],
                    $val['member_name'],
                    $val['member_phone'],
                    $val['name'],
                    $val['goods_name'],
                    $val['goods_money'],
                    $val['order_number'],
                    $val['order_bonus'],
                    $remarks,
                    $val['buy_time'],
                    $status
                );
            }
            $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
            $env = $con->env;
            if ($env == 'CLOUD'){
                $temp_file = tempnam(sys_get_temp_dir(),"1xlsx");  //临时文件
                $a = Excel::create('业绩订单',function($excel) use ($arr){
                    $excel->sheet('业绩订单', function($sheet) use ($arr){
                        $sheet->rows($arr);
                    });
                })->string('xlsx');
                file_put_contents($temp_file,$a);
                $data['code'] = 3;
                $data['name'] = '业绩订单.xlsx';
                $data['data'] = $temp_file;
                return $data;
            }else{
                Excel::create('业绩订单',function($excel) use ($arr){
                    $excel->sheet('业绩订单', function($sheet) use ($arr){
                        $sheet->rows($arr);
                    });
                })->export('xlsx');
            }
        }
        $this->returnData = ErrorCode::$admin_enum['fail'];
        $this->returnData['msg'] = '操作失败';
        return $this->return_result($this->returnData);
    }

    /* 业绩录入 */
    public function achievementAdd(Request $request, $id){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $memberModel = new MemberBase();
        $info = $memberModel->getMemberList(["me.realname", "m.mobile"], [["m.id", "=", $id]]);
        $data['member_name'] = $info[0]['realname'] ?: $request->post("name", '');
        $data['member_phone'] = $info[0]['mobile'];
        $data['member_id'] = $id;
        $data['admin_users_id'] = $this->AU['id'];
        $data['goods_money'] = $request->post("goods_money", 0);
        $data['goods_name'] = $request->post("goods_name", "");
        $data['order_number'] = $request->post("order_number", 0);
        $data['goods_price'] = $request->post("goods_price", 0);
        $data['sbr_id'] = 0;
        $data['after_sale_id'] = $request->post("after_sale_id", 0);
        $data['sale_proof'] = $request->post("sale_proof", 0);
        $data['remarks'] = $request->post("remarks", "");
        $data['buy_time'] = $request->post("buy_time", "");
        $data['buy_length'] = $request->post("buy_length", "");
        $data['number_sn'] = date('YmdHis') . rand(1, 9);
        $data['status'] = 0;
        $achievementModel = new Achievement();
        $res = $achievementModel->achievementInsert($data);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = "录入失败";
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = "录入成功";
        return $this->return_result($this->returnData);
    }

    /* 业绩转移 */
    public function exchangeOrder(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $touid = $request->input("exchange_user");
        if($touid==null){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '转移管理员不能为空';
            return $this->return_result($this->returnData);
        }
        $list = $request->input("exchange_list");
        if($list==null || $list=="0"){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '转移订单不能为空';
            return $this->return_result($this->returnData);
        }
        $list = explode(',',$list);
        foreach ($list as $k=>$v){
            if($v=="0"){
                unset($list[$k]);
            }
        }

        $achievementModel = new Achievement();
        $result = $achievementModel->getBaseAchievementList(['id'],[['id','in',$list]]);
        if(!is_array($result)){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '无权转移';
            return $this->return_result($this->returnData);
        }
        $data_list = [];
        foreach ($result as $key=>$value){
            $data_list[] = $value['id'];
        }
        $bool = $achievementModel->achievementUpdate($data_list,['admin_users_id'=>$touid]);
        if(!$bool){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '修改失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '修改成功';
        return $this->return_result($this->returnData);
    }
    
    /* 业绩订单删除 */
    public function delete($id){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $achievementModel = new Achievement();
        $res = $achievementModel->achievementDelete($id);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '删除失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '删除成功';
        return $this->return_result($this->returnData);
    }

    // 个人业绩
    public function getPersonalAchievementStatistics(Request $request){
        if ($this->returnData['code'] > 0){
           return $this->returnData;
        }
        $page = $request->page_no ? : 1;
        $pageSize = $request->page_size ?: 10;
        $startTime = Achievement::query()->where(["admin_users_id" => $this->AU['id'], "mall_id" => $request->mallData['id']])
            ->orderBy("id", "asc")
            ->value("buy_time");
        $startTime = $startTime ? strtotime($startTime) : time(); // 业绩开始时间
        $number = Carbon::now()->diffInMonths(Carbon::createFromTimestamp($startTime)) + 1; // 一共有多少个月
        $endTime = mktime(23, 59, 59, date('m') - ($pageSize * ($page - 1)), date('t'), date('Y')); // 结束时间
        $dateList = $this->getDateRange($startTime, $endTime, $pageSize);
        $this->returnData['data'] = ["rows" => [], "total" => $number];
        $userData = AdminUser::query()->where("id", $this->AU['id'])->select("id", "name")->first()->toArray();
        foreach ($dateList as $date){
            $item = [
                "id" => $userData['id'], 'userName' => $userData['name'], "dateTime" => date("Y-m", strtotime($date[0])), "totalSaleMoney" => 0,
                "totalCommissionMoney" => 0, "totalBonusMoney" => 0
            ];
            $model = Achievement::query()->where(["admin_users_id" => $this->AU['id'], "status" => 1, "ach_state" => 0, "mall_id" => $request->mallData['id']])
                ->whereBetween("buy_time", $date)
                ->selectRaw("sum(`goods_money`) as totalSaleMoney,sum(`order_bonus`) as totalCommissionMoney")
                ->first();
            if(!empty($model)){
                $item['totalSaleMoney'] = $model->totalSaleMoney ?: 0;
                $item['totalCommissionMoney'] = $model->totalCommissionMoney ?: 0;
            }
            $item['totalBonusMoney'] = AfterSale::query()->where(["after_sale_id" => $this->AU['id'], "mall_id" => $request->mallData['id']])
                ->whereBetween("created_at", $date)
                ->sum("bonus_royalty");
            $this->returnData['data']['rows'][] = $item;
        }
        return $this->return_result($this->returnData);
    }

    // 全体业绩
    public function getWholeAchievementStatistics(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $page = $request->page_no ? : 1;
        $pageSize = $request->page_size ?: 10;
        if($request->date){
            $startTime = Carbon::create($request->date, 1, 1, 0, 0, 0)->getTimestamp();
            $endTime = Carbon::create($request->date, 12, 31, 23, 59, 59)->getTimestamp();
            $number = 12;
        }else {
            $startTime = Achievement::query()->where("mall_id", $request->mallData['id'])->orderBy("id", "asc")->value("buy_time");
            $startTime = $startTime ? strtotime($startTime) : time(); // 业绩开始时间
            $number = Carbon::now()->diffInMonths(Carbon::createFromTimestamp($startTime)) + 1; // 一共有多少个月
            $endTime = mktime(23, 59, 59, date('m') - ($pageSize * ($page - 1)), date('t'), date('Y')); // 结束时间
        }
        $dateList = $this->getDateRange($startTime, $endTime, $pageSize);
        $this->returnData['data'] = ["rows" => [], "total" => $number];
        if(!empty($dateList)) {
            if($this->AU['position'] != "超级管理员"){
                $adminUserModel = new UserBase();
                $userList = $adminUserModel->getAdminSubuser($this->AU['id']);
            }
            foreach ($dateList as $date) {
                $item = [
                    "dateTime" => date("Y-m", strtotime($date[0])), "totalSaleMoney" => 0, "totalCommissionMoney" => 0, "totalBonusMoney" => 0
                ];
                $db = Achievement::query()->where(["status" => 1, "ach_state" => 0, "mall_id" => $request->mallData['id']])
                    ->whereBetween("buy_time", $date);
                if(!empty($userList)){
                    $db->whereIn('admin_users_id', $userList);
                }
                $model = $db->selectRaw("sum(`goods_money`) as totalSaleMoney,sum(`order_bonus`) as totalCommissionMoney")->first();
                if (!empty($model)) {
                    $item['totalSaleMoney'] = $model->totalSaleMoney ?: 0;
                    $item['totalCommissionMoney'] = $model->totalCommissionMoney ?: 0;
                }
                $db = AfterSale::query()->whereBetween("created_at", $date)->where("mall_id", $request->mallData['id']);
                if(!empty($userList)){
                    $db->whereIn('after_sale_id', $userList);
                }
                $item['totalBonusMoney'] = $db->sum("bonus_royalty");
                $this->returnData['data']['rows'][] = $item;
            }
        }
        return $this->return_result($this->returnData);
    }

    public function getDateRange($startTime, $endTime, $pageSize = 0, $sortType = "desc"){
        $dateList = [];
        $endTime = $endTime ?: mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        do{
            $value = [date("Y-m-01 00:00:00", $endTime), date("Y-m-t 23:59:59", $endTime)];
            $endTime = $endTime - (strtotime($value[1]) - strtotime($value[0])) - 86400;
            $dateList[] = $value;
            if($pageSize && count($dateList) == $pageSize){
                break;
            }
        }while($endTime >= $startTime);
        return $sortType == "asc" ? array_reverse($dateList) : $dateList;
    }

    // 全体业绩详情
    public function getAchievementStatisticsInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->dateTime){
            return ErrorCode::code("params_not_exist", "日期");
        }
        $page = $request->page_no ? : 1;
        $pageSize = $request->page_size ?: 10;
        $startTime = strtotime(date("Y-m-01 00:00:00", strtotime($request->dateTime)));
        $endTime = strtotime(date("Y-m-t 23:59:59", strtotime($request->dateTime)));
        $number = 1;
        $dateList = $this->getDateRange($startTime, $endTime, $pageSize);
        $this->returnData['data'] = ["rows" => [], "total" => $number];
        $db = AdminUser::query()->where("mall_id", $request->mallData['id']);
        if($this->AU['position'] != "超级管理员"){
            $adminUserModel = new UserBase();
            $userList = $adminUserModel->getAdminSubuser($this->AU['id']);
            $db->whereIn("id", $userList);
        }
        $this->returnData['data']['total'] = $db->count();
        $userData = $db->select("id", "name")->skip(($page-1) * $pageSize)->take($pageSize)->get();
        if(!empty($userData)){
            $userData = $userData->toArray();
            foreach ($userData as $val){
                foreach ($dateList as $date) {
                    $item = [
                        "id" => $val['id'], "userName" => $val['name'], "dateTime" => date("Y-m", strtotime($date[0])), "totalSaleMoney" => 0,
                        "totalCommissionMoney" => 0, "totalBonusMoney" => 0
                    ];
                    $model = Achievement::query()->where(["status" => 1, "ach_state" => 0, "admin_users_id" => $val['id']])->whereBetween("buy_time", $date)
                        ->selectRaw("sum(`goods_money`) as totalSaleMoney,sum(`order_bonus`) as totalCommissionMoney")
                        ->first();
                    if (!empty($model)) {
                        $item['totalSaleMoney'] = $model->totalSaleMoney ?: 0;
                        $item['totalCommissionMoney'] = $model->totalCommissionMoney ?: 0;
                    }
                    $item['totalBonusMoney'] = AfterSale::query()->whereBetween("created_at", $date)->where('after_sale_id', $val['id'])->sum("bonus_royalty");
                    $this->returnData['data']['rows'][] = $item;
                }
            }
        }
        return $this->return_result($this->returnData);
    }
}